package com.douyin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.douyin.constant.JwtClaimsConstant;
import com.douyin.entity.UserSubscribe;
import com.douyin.entity.video.Type;
import com.douyin.entity.video.Video;
import com.douyin.entity.video.VideoShare;
import com.douyin.exception.BaseException;
import com.douyin.holder.UserHolder;
import com.douyin.properties.JwtProperties;
import com.douyin.service.IUserService;
import com.douyin.service.TypeService;
import com.douyin.service.VideoService;
import com.douyin.utils.JwtUtil;
import com.douyin.utils.R;
import com.douyin.vo.BasePage;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/douyin/index")
public class IndexController {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private TypeService typeService;

    @Autowired
    private VideoService videoService;
    @Autowired
    private IUserService userService;
    @GetMapping("/types")
    public R getTypes(){
        List<Type> types = typeService.list(new LambdaQueryWrapper<Type>());
        return R.ok().data(types);
    }

    @GetMapping("/video/type/{typeId}")
    public R getVideoByTypeId(@PathVariable Long typeId){

        return R.ok().data(videoService.getVideoByTypeId(typeId));
    }

    @GetMapping("/video/{videoId}")
    public R getVideoById(@PathVariable Long videoId){
        return R.ok().data(videoService.getById(videoId));
    }
    //兴趣推送
    @GetMapping("/pushVideos")
    public R pushVideos(HttpServletRequest request){
        final Long userId = getUserId(request);
        return R.ok().data(videoService.pushVideos(userId));
    }

    @PostMapping("/share/{videoId}")
    public R shareVideo(@PathVariable Long videoId,HttpServletRequest request){
        String ip = null;
        if (request.getHeader("x-forwarded-for") == null)
            ip = request.getRemoteAddr();
        else
            ip = request.getHeader("x-forwarded-for");
        final VideoShare videoShare = new VideoShare();

        videoShare.setVideoId(videoId);
        videoShare.setIp(ip);
        if (checkToken(request)) {
            videoShare.setUserId(getUserId(request));
        }
        videoService.shareVideo(videoShare);
        return R.ok();
    }

    @GetMapping("/search")
    public R searchVideo(@RequestParam(required = false) String searchName, BasePage basePage,HttpServletRequest request){
        return R.ok().data(videoService.searchVideo(searchName,basePage,getUserId(request)));
    }

    @GetMapping("/search/history")
    public R searchHistory(HttpServletRequest request){
        final Long userId = getUserId(request);
        return R.ok().data(userService.getSearchHistory(userId));
    }

    @DeleteMapping ("/search/history")
    public R deleteSearchHistory(HttpServletRequest request){
        final Long userId = getUserId(request);
        userService.deleteSearchHistory(userId);
        return R.ok().data("删除成功");
    }

    @GetMapping("/video/user")
    public R getVideoByUser(@RequestParam(required = false) Long userId,BasePage basePage,HttpServletRequest request){
        userId = userId==null?getUserId(request):userId;
        return R.ok().data(videoService.getVideoByUserId(userId,basePage));
    }

    @GetMapping("/video/hot/rank")
    public R getHotRank(){
        return R.ok().data(videoService.getHotRank());
    }
    @GetMapping("/video/hot")
    public R getHotVideo(){
        return R.ok().data(videoService.getHotVideo());
    }

    @GetMapping("/video/similar")
    public R pushVideoSimilar(Video video){
        return R.ok().data(videoService.listSimilarVideo(video));
    }

    public boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader(jwtProperties.getTokenName());
            if(ObjectUtils.isEmpty(jwtToken)) return false;
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    public Long getUserId(HttpServletRequest request) {
        String token = request.getHeader(jwtProperties.getTokenName());
        if (ObjectUtils.isEmpty(token)) return null;
        Claims claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(), token);
        return Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
    }
}
